﻿using System;
using System.Collections;
using System.Configuration;
using System.Data; 
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using System.Text;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Workflow; 

namespace Runda.CMS.Portal.ContractManage
{
    public partial class ContractChangeEdit : WorkflowPage
    {
        public Guid ContractID
        {
            get
            {
                if (ViewState["ContractID"] == null) return Guid.Empty;
                else return new Guid(ViewState["ContractID"].ToString());
            }
            set
            {
                txtContractID.Value = value.ToString();
                ViewState["ContractID"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Type";
                parm.ColumnType = DbType.Int32;
                parm.ParameterName = "@Type";
                parm.ParameterValue = System.Convert.ToInt32(ContractEnumerator.ContractParms.contractAttr);
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                listContractAttribute.DataSource = new SysDictionaryBll().GetAll<SysDictionaryEntity>(parms);
                listContractAttribute.DataTextField = "Code";
                listContractAttribute.DataValueField = "ID";
                listContractAttribute.DataBind();
                if (Request.QueryString["AssociationID"] != null)
                {
                    ContractBll bll = new ContractBll();

                    ContractID = bll.CopyContract(new Guid(Request.QueryString["AssociationID"]));
                    InitForm();

                    LoadItem();
                }
                else
                    lnkbtnSubmit.Enabled = false;
            }
        }

        private void InitForm()
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();

            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
                txtContractCode.Text = entity.ContractCode;
                listContractAttribute.SelectedValue = entity.ContractAttribute.ToString();
                txtContractApplyDate.Text = entity.ContractApplyDate.ToShortDateString();
                txtContractEstimateSignDate.Text = entity.ContractEstimateSignDate.ToShortDateString();

                listContractType.SelectedValue = entity.ContractType;
                txtContractStatement.Text = entity.ContractStatement;
                //txtContractPeriod.Text = entity.ContractPeriod.ToString();
                txtGivenMaterialdesc.Text = entity.GivenMaterialdesc;
                //txtGivenMaterialCost.Text = entity.GivenMaterialCost.ToString();
                //txtCapitalCost.Text = entity.CapitalCost.ToString();

                if (entity.CustomerID != Guid.Empty)
                {
                    CtrtCustomerEntity userEntity = new CtrtCustomerBll().Get<CtrtCustomerEntity>(entity.CustomerID);
                    hiddenuserName.InnerText = userEntity.CustomerName;
                    hiddenUserID.Value = userEntity.CustomerID.ToString();
                }

                if (entity.InstanceID != Guid.Empty)
                {
                    BindWorkflow(entity.InstanceID);
                }
                if (entity.Status == 1 || entity.Status == 3)
                {
                    lnkbtnSave.Enabled = false;
                    lnkbtnSaveAndClose.Enabled = false;
                    lnkbtnSaveAndNew.Enabled = false;
                    lnkbtnSubmit.Enabled = false;
                }
            }
            else
            {
                lnkbtnSubmit.Enabled = false;
            }
        }

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandcloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                ContractID = Guid.Empty;
                txtContractCode.Text = "";
                txtContractApplyDate.Text = "";
                txtContractEstimateSignDate.Text = "";
                txtContractStatement.Text = "";
                //txtContractPeriod.Text = "";
                txtGivenMaterialdesc.Text = "";
                //txtGivenMaterialCost.Text = "";
                //txtCapitalCost.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool Save(ref string Message)
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();
            //try save info
            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
            }
            else
            {
                entity = new CtrtContractEntity();
                ContractID = entity.ContractID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;

                entity.Status = (int)Enumerator.ContractStatus.Draft;
            }

            if (hiddenUserID.Value != string.Empty)
                entity.CustomerID = new Guid(hiddenUserID.Value);
            entity.ContractCode = txtContractCode.Text;
            if (listContractAttribute.SelectedValue != string.Empty)
                entity.ContractAttribute = new Guid(listContractAttribute.SelectedValue);
            if (txtContractApplyDate.Text.Trim() != string.Empty)
                entity.ContractApplyDate = Convert.ToDateTime(txtContractApplyDate.Text);
            if (txtContractEstimateSignDate.Text.Trim() != string.Empty)
                entity.ContractEstimateSignDate = Convert.ToDateTime(txtContractEstimateSignDate.Text);
            entity.ContractType = listContractType.SelectedValue;
            entity.ContractStatement = txtContractStatement.Text;
            //if (txtContractPeriod.Text != string.Empty)
            //    entity.ContractPeriod = Convert.ToInt32(txtContractPeriod.Text);
            entity.GivenMaterialdesc = txtGivenMaterialdesc.Text;
            //if (txtGivenMaterialCost.Text != string.Empty)
            //    entity.GivenMaterialCost = Convert.ToDecimal(txtGivenMaterialCost.Text);
            //if (txtCapitalCost.Text != string.Empty)
            //    entity.CapitalCost = Convert.ToDecimal(txtCapitalCost.Text);

            bll.InsertOrUpdate(entity);

            txtContractID.Value = ContractID.ToString();

            return true;
        }

        private void LoadItem()
        {
            if (ContractID == Guid.Empty) return;

            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = null;

            parm = new SqlDbParameter();
            parm.ColumnName = "ContractID";
            parm.ColumnType = DbType.Guid;
            parm.ParameterName = "@ContractID";
            parm.ParameterValue = ContractID;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            List<CtrtContractItemEntity> list = new CtrtContractItemBll().GetAll<CtrtContractItemEntity>(parms);

            RepeaterContractItem.DataSource = list;
            RepeaterContractItem.DataBind();
        }

        protected void RepeaterContractItem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "refersh")
            {
                LoadItem();
            }
        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);

            IWorkflowInstance instance = this.GetInstance(Runda.CMS.Common.Utility.DeclareHelper.ModelConstant.ModelContract);
            instance.OnNextRouting += new EventHandler<RoutingEventArgs>(instance_OnNextRouting);

            if (entity.InstanceID == Guid.Empty)
            {
                instance.Start(ContractID,"合同编号为"+entity.ContractCode);
            }
            else
            {
                instance.ReStart(entity.InstanceID);
            }

            //更新原合同为作废状态
            entity = bll.Get<CtrtContractEntity>(new Guid(Request.QueryString["AssociationID"]));
            entity.Status = (int)Enumerator.ContractStatus.Nullify;
            bll.Update(entity);

            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        void instance_OnNextRouting(object sender, RoutingEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if (e.RoutingEntity.NextActivityID != Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = null;
                parm = new SqlDbParameter();
                parm.ColumnName = "ActivityID";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@ActivityID";
                parm.ParameterValue = e.RoutingEntity.NextActivityID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Like;
                parms.Add(parm);

                WflActivityCheckersBll wacbll = new WflActivityCheckersBll();
                List<WflActivityCheckersEntity> list = wacbll.GetAll<WflActivityCheckersEntity>(parms);

                foreach (WflActivityCheckersEntity c in list)
                {
                    sb.Append(c.UserName).Append("(").Append(c.Account).Append(")").Append(",");
                }
            }
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            entity.InstanceID = e.InstanceID;
            entity.NextCheckers = sb.ToString().TrimEnd(',');
            entity.Status = (int)Enumerator.ContractStatus.Submit;
            bll.Update(entity);
        }

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Runda.CMS.Workflow.ActivityStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }

        private void BindWorkflow(Guid InstanceID)
        {
            List<WflInstanceRoutingEntity> list = new WflInstanceRoutingBll().GetAll<WflInstanceRoutingEntity>(" and InstanceID = '" + InstanceID + "' and CheckStatus != 1 order by CheckDate");

            RepeaterApprove.DataSource = list;
            RepeaterApprove.DataBind();
        }

    }
}
